// import { chromium } from 'playwright'
import fsp from 'fs/promises'
import fse from 'fs-extra'
import { chromium } from 'playwright-extra'
import stealth from 'puppeteer-extra-plugin-stealth'
import md5 from 'md5'
import path from 'node:path'
import { cacheDir } from '../config.js'

chromium.use(stealth())

class PlaywrightAPI {
  constructor() {
    this.launch()
  }

  launch() {
    this.getContext()
  }

  async getContext() {
    if (this.context) return this.context

    // await fs.copy('C:/Users/llz/AppData/Local/Google/Chrome/User Data', './data/cache')

    const context = await chromium.launchPersistentContext(path.join(cacheDir, 'playwright'), {
      // headless: true,
      headless: false,
      // acceptDownloads: true, // 允许下载文件到缓存目录
      // permissions: ["geolocation"], // 持久化权限设置
      // storageState: "./auth.json", // 保存/加载登录状态
    })

    this.context = context

    return context
  }

  async getHtml(url, options) {
    const { context } = this
    const { cache } = {
      ...options,
      cache: true,
    }

    const cacheKey = md5(url) + '.html'
    const cacheFile = path.join(cacheDir, 'web', cacheKey)
    let cacheData

    if (cache) {
      const cacheExists = await fse.pathExists(cacheFile)
      if (cacheExists) {
        cacheData = await fse.readFile(cacheFile, 'utf-8')
        return cacheData
      }
    }

    let html

    const page = await context.newPage()
    await page.goto(url, {
      timeout: 0,
    })

    // 获取整个页面的 HTML
    html = await page.content()

    if (cache) {
      await fse.ensureDir(path.parse(cacheFile).dir)
      await fsp.writeFile(cacheFile, html)
    }

    await page.close()

    return html
  }
}

export default new PlaywrightAPI()
